<script setup>

import {ElButton, ElCard, ElInput, ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Refresh} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {userInfoStore} from "@/store/userInfoStore.js";
import {GetUserList,DeleteUser} from "@/api/user.js";
import { Picture as IconPicture } from '@element-plus/icons-vue'
import AddUserComponent from "@/components/admin/userAdmin/AddUserComponent.vue";
import UpdateUserComponent from "@/components/admin/userAdmin/UpdateUserComponent.vue";

const total = ref(20) //总条数
//分页条数据模型
const form = ref({
  id: userInfoStore().info.id, //查询人id
  nickname: '', //用户昵称
  user_profile: '',//用户简介
  user_role: '', // 用户角色
  current : 1, //当前页
  pageSize: 3,//每页条数
  sortField: '',//排序字段
  sortOrder: ''//排序顺序
})
const fields = ref(
  {
          "用户ID":"id",
          "用户昵称":"nickname",
          "用户角色":"user_role"
      }
)
const tableData = ref([])

const clearForm = () => {
  form.value={
    id: userInfoStore().info.id, //查询人id
    nickname: '', //用户昵称
    user_profile: '',//用户简介
    user_role: '', // 用户角色
    current : 1, //当前页
    pageSize: 3,//每页条数
    sortField: '',//排序字段
    sortOrder: ''//排序顺序
  }
}

const fetchUserList = async () => {
  const params = {
    id: form.value.id>0?form.value.id:null,
    nickname: form.value.nickname===""?null:form.value.nickname,
    user_profile: form.value.user_profile===""?null:form.value.user_profile,//用户简介
    user_role: form.value.user_role===""?null:form.value.user_role, // 用户角色
    sortField: form.value.sortField===""?null:form.value.sortField,//排序字段
    sortOrder: form.value.sortOrder===""?null:form.value.sortOrder,//排序顺序
    current: form.value.current,
    pageSize: form.value.pageSize
  }
  //获取用户列表
  const answer = await GetUserList(params);
  tableData.value = answer.data.items;
  total.value = answer.data.total;
  console.log("搜索成功！")
  ElMessage.success("搜索成功！");
  console.log(tableData.value)
}

onMounted(async ()=>{
  await fetchUserList();
  console.log(tableData.value)
})
//当每页条数发生了变化，调用此函数
const onSizeChange = async (size) => {
  form.value.pageSize = size;
  fetchUserList();
};
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
  form.value.current = num;
  await fetchUserList()
};

//添加用户
const addUserRef = ref(null);

const openAddUserDialog = () => {
  if (addUserRef.value) {
    addUserRef.value.showAddUserDialog();
  }
};
//更新用户
const updateUserRef = ref(null);
const openUpdateUserDialog = (row) => {
  if (updateUserRef.value) {
    updateUserRef.value.showUpdateUserDialog(row);
  }
}
//删除用户
const DeleteForUser = async (row)=>{
  ElMessageBox.confirm(
      row.isDelete===0?'此操作将删除该应用，是否确认删除？':'此操作将恢复该用户，是否确认恢复？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        console.log(row.id)
        await DeleteUser(row.id);
        await fetchUserList();
        if(row.isDelete===0) {
          ElMessage.success("删除成功！")
        }else{
          ElMessage.success("恢复成功！")
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '按钮取消!',
        })
      })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户管理</span>
        <div class="extra">
          <!--# todo 这个地方当管理员点击添加用户的时候要弹出一个添加用户的框-->
          <el-button type="primary" @click="openAddUserDialog">添加用户</el-button>
          <AddUserComponent ref="addUserRef" @call-parent="fetchUserList"/>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline class="user-list">
      <!--todo 这里要与后端的搜索用户的数据一致，添加一样多的搜索框 -->
<!--      <el-form-item label="用户ID：">-->
<!--        <el-input v-model="form.id" />-->
<!--      </el-form-item>-->
      <el-form-item label="用户呢称：">
        <el-input v-model="form.nickname" />
      </el-form-item>
      <el-form-item label="用户角色：">
        <el-select placeholder="请选择" v-model="form.user_role" style="width: 240px">
          <el-option label="所有" value="所有"></el-option>
          <el-option label="管理员" value="admin"></el-option>
          <el-option label="普通用户" value="user"></el-option>
          <el-option label="被禁用户" value="ban"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序字段：">
        <el-select placeholder="请选择" v-model="form.sortField" style="width: 240px">
          <el-option v-for="([label, value]) in Object.entries(fields)" :key="value" :label= "label" :value="value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序方式：">
        <el-select placeholder="请选择" v-model="form.sortOrder" style="width: 240px">
          <el-option label="升序" value="asc"></el-option>
          <el-option label="降序" value="desc"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户简介" >
        <el-input v-model="form.user_profile" type="textarea" style="width: 360px"/>
      </el-form-item>
      <el-form-item class="button-group">
        <el-button type="primary" @click="fetchUserList"
        >搜索</el-button
        >
        <el-button
            @click="
            clearForm();
            fetchUserList();
            ElMessage.success('重置成功！')
          "
        >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
          type="index"
          label="序号"
          width="50"
      ></el-table-column>
      <el-table-column
          label="用户ID"
          prop="id"
      ></el-table-column>
      <el-table-column
          label="账户"
          prop="username"
      ></el-table-column>
      <el-table-column
          label="用户昵称"
          prop="nickname"
      ></el-table-column>
      <el-table-column label="头像" prop="user_pic">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.user_pic||'D:\\WebStorm 2024.1.5\\repository\\fronted\\src\\assets\\avatar.jpg'"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[scope.row.user_pic||'D:\\WebStorm 2024.1.5\\repository\\fronted\\src\\assets\\avatar.jpg']"
              :preview-teleported="true"
              show-progress
              fit="cover"
          >
            <template #error>
            <div class="image-slot">
              <el-icon><icon-picture /></el-icon>
            </div>
          </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="简介" prop="user_profile"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="角色" prop="user_role">
        <template #default="{ row }">
          <el-text class="mx-1" type="primary" v-if="row.user_role === 'admin'">管理员</el-text>
          <el-text class="mx-1" type="info" v-else-if="row.user_role === 'user'">普通用户</el-text>
          <el-text class="mx-1" type="danger" v-else-if="row.user_role === 'ban'">异常用户</el-text>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" prop="create_time"> </el-table-column>
      <el-table-column label="更新时间" prop="update_time"> </el-table-column>
      <el-table-column label="状态" prop="isDelete">
        <template #default="{ row }">
          <el-text class="mx-1" type="success" v-if="row.isDelete === 0">正常</el-text>
          <el-text class="mx-1" type="danger" v-else>已删除</el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
              :icon = Edit
              circle
              plain
              type="primary"
              @click="openUpdateUserDialog(row)" >  </el-button>
          <UpdateUserComponent ref="updateUserRef" @call-parent="fetchUserList"/>
          <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="DeleteForUser(row)"
              v-if="row.isDelete === 0"
          ></el-button>
          <el-button
              :icon="Refresh"
              circle
              plain
              type="success"
              @click="DeleteForUser(row)"
              v-if="row.isDelete === 1"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
        v-model:current-page="form.current"
        v-model:page-size="form.pageSize"
        :page-sizes="[3, 5, 10, 15]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .user-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px; /* 表单项之间的间距 */
    align-items: center;
  }

  .user-list el-form-item {
    margin-bottom: 0; /* 移除默认的底部间距 */
  }

  .button-group {
    margin-left: auto; /* 将按钮组推到右侧 */
  }

  el-image {
    position: relative;
    z-index: 1;
  }
  .el-image-viewer__img {
    z-index: 9999 !important;
  }
}
</style>


